package com.xtc.netty.protocol.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author Administrator
 */
public class HttpFileServer {
    public static final String DEFAULT_URL = "/netty-tomcat/src/main/java/com/xtc/netty/";

    public void run(final int port, final String url) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap server = new ServerBootstrap();
            server.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    // Http请求消息解码器
                                    .addLast("http-decoder", new HttpRequestDecoder())
                                    // 将多个消息转化为单一的HTTPFullRequest或者FullHTTPResponse
                                    .addLast("http-aggregator", new HttpObjectAggregator(65536))
                                    // Http响应消息进行编码
                                    .addLast("http-encoder", new HttpResponseEncoder())
                                    // 异步支持大文件的传输
                                    .addLast("http-chunked", new ChunkedWriteHandler())
                                    // 文件服务器处理类
                                    .addLast("fileServerHandler", new HttpFileServerHandler(url));
                        }
                    })
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture future = server.bind(port).sync();

            System.out.println("Http 文件目录服务器已启动，网址是：127.0.0.1:" + port + url);

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        int port = 9090;
        String url = DEFAULT_URL;
        if (args != null) {
            if (args.length > 0) {
                port = Integer.parseInt(args[0]);
            }

            if (args.length > 1) {
                url = args[1];
            }
        }
        new HttpFileServer().run(port, url);
    }
}
